package com.zbb.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbb.user.mapper.UserMapper;
import com.zbb.user.model.dto.UserLoginDto;
import com.zbb.user.model.po.UserExt;
import com.zbb.user.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    ApplicationContext applicationContext;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserLoginDto userLoginDto = null;
        try {
            //将认证参数转为 AuthParamsDto 类型
            userLoginDto = JSON.parseObject(s, UserLoginDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }

        //根据认证类型调用参数
        AuthService passwordAuthservice = applicationContext.getBean("password_authservice", AuthService.class);
        UserExt userExt = passwordAuthservice.execute(userLoginDto);


        return getUserPrincipal(userExt);
    }

    public UserDetails getUserPrincipal(UserExt user){
        //用户权限,如果不加报 Cannot pass a null GrantedAuthority collection
        String[] authorities = {"p1"};
        String password = user.getPassword();
        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将 user 对象转 json
        String userString = JSON.toJSONString(user);
        //创建 UserDetails 对象
        UserDetails userDetails =
                User.withUsername(userString).password(password ).authorities(authorities).build();
        return userDetails;
    }





}
